<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-09-06
 * Time: 17:58
 */

namespace App\Model\Backstage;


use App\Model\Base;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redis;

class Log extends Base
{
    protected $log_table;

    public function __construct()
    {
        $this->log_table = 'log_'.$this->branch_id; // 日志表
//        $this->log_table = 'log';
    }

    /**根据不同的日志类型  查询该类型下面的日志列表
     * @param array $where
     * @param $pageLimit
     * @return bool
     */
    public function loglist($where = [], $pageLimit)
    {
        $list = DB::table('log_'.Auth::user()['u_b_id'])
            ->leftJoin('user', 'l_u_id', '=', 'u_id')
            ->leftJoin('department', 'l_b_id', '=', 'id')
            ->where($where)
            ->select('l_id', 'name', 'u_username', 'l_content', DB::raw('from_unixtime(l_create_time) as l_create_time'))
            ->orderBy('l_id', 'desc')
            ->paginate($pageLimit);
        if (sizeof($list) == 0) {
            return false;
        }
        return $list;
    }

    /**添加日志
     * @param $bId 部门ID
     * @param $uId 用户ID
     * @param $type 操作类型
     * @param $content 操作内容
     * @return mixed
     */
    public function addlog($bId, $uId, $type, $content, $bran_id = '')
    {
        if ($bran_id) {
            $log_table = 'log_'.$bran_id;
        } else {
            if (Auth::user()['u_b_id']) {
                $log_table = 'log_'.Auth::user()['u_b_id'];
            } else {
                $apptoken = $_REQUEST['apptoken'];
                $data = explode(',', Redis::get($apptoken));
                $branch_id  = $data[0];    //公司ID
                $log_table = 'log_'.$branch_id;
            }

        }
        return DB::table($log_table)->insertGetId([
            'l_b_id'        => $bId,
            'l_u_id'        => $uId,
            'l_type'        => $type,
            'l_content'     => $content,
            'l_create_time' => time()
        ]);
    }

}